<?php
require_once 'vendor/autoload.php';
use \Firebase\JWT\JWT;
use Firebase\JWT\Key;

class BaseController extends Controller{
	public $layout = "layout.html";
	public $uid;
	public $token;
	function __construct()
	{
		parent::__construct();
	}

	

	function init(){
		header("Content-type: text/html; charset=utf-8");
		require(APP_DIR.'/protected/include/functions.php');	
		$__controller = isset($_REQUEST['c']) ? strtolower($_REQUEST['c']) : 'main';
		$__action     = isset($_REQUEST['a']) ? strtolower($_REQUEST['a']) : 'index';

		
		$this->_controller = $__controller;
		$this->_action = $__action;
	}

	/**
     * 从Token中解析用户ID
     */
    public function getLoginUserId(){
        try {
            $this->token = getToken();
            if (empty($this->token)) {
                throw new Exception('Token为空');
            }
            $secretKey = $GLOBALS['JWT_SECRET_KEY'];
            $key = new Key($secretKey , 'HS256');
            $decoded = JWT::decode($this->token, $key);
            $userId = $decoded->userId;
            return $userId;
        } catch (Exception $e) {
            return false;
        }
    }

    function tips($msg, $url){
    	$url = "location.href=\"{$url}\";";
		echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><script>function sptips(){alert(\"{$msg}\");{$url}}</script></head><body onload=\"sptips()\"></body></html>";
		exit;
    }
    function jump($url, $delay = 0){
        echo "<html><head><meta http-equiv='refresh' content='{$delay};url={$url}'></head><body></body></html>";
        exit;
	}
	function result($code=1,$msg='',$data=array()){
		echo json_encode(array(
			'code'=>$code,
			'msg'=>$msg,
			'data'=>$data
		));
		exit();
	}
	/**
	 * 写log
	 * @param $level ERROR\WARN\NOTICE\INFO\DEBUG
	 * @param $msg 日志内容
	 */
	function wlog($level,$msg){
		$this->slog = new spLog();
		$this->slog->log($msg,$level);
	}

    //查看访问权限
	function checkAuth($uid)
    {
        $uid = empty($uid) ? $_COOKIE['kp_uid'] : $uid;
        if (empty($uid)) {
            return false;
        }
        if ($this->_controller != 'main') {
            // if (empty($this->role)) {
            //     $user = new User();
            //     $udata = $user->find(array("id" => $uid), '', 'id,role');
            //     $this->role = $udata["role"];
            //}
            $role = explode(',', $this->role);
            if (!in_array('admin', $role)) {
                return false;
            }
        }
        return true;
    }
} 